import Mock from 'mockjs';

// 生成模拟的用户数据
const userList = Mock.mock({
  'list|100': [
    {
      'id|+1': 1,
      'name': '@cname',
      'username': '@last',
      'email': '@email',
      'phone': /^1[3-9]\d{9}$/,
      'address': '@county(true)',
      'createTime': '@datetime',
      'avatar': '@image("200x200", "#50B347", "#FFF", "Mock.js")',
      'role|1': ['admin', 'user', 'guest'],
      'status|1': [0, 1, 2],
      'age|18-60': 1
    }
  ]
});

// 定义mock接口
const userMock = {
  // 获取用户列表
  'GET /api/users': (req: any, res: any) => {
    const { page = 1, pageSize = 10 } = req.query;
    const start = (page - 1) * pageSize;
    const end = page * pageSize;
    const total = userList.list.length;
    const data = userList.list.slice(start, end);
    
    res.json({
      code: 200,
      message: 'success',
      data: {
        list: data,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  },
  
  // 获取用户详情
  'GET /api/users/:id': (req: any, res: any) => {
    const { id } = req.params;
    const user = userList.list.find((item: any) => item.id === parseInt(id));
    
    if (user) {
      res.json({
        code: 200,
        message: 'success',
        data: user
      });
    } else {
      res.json({
        code: 404,
        message: '用户不存在'
      });
    }
  },
  
  // 添加用户
  'POST /api/users': (req: any, res: any) => {
    const newUser = req.body;
    newUser.id = userList.list.length + 1;
    newUser.createTime = new Date().toISOString();
    userList.list.push(newUser);
    
    res.json({
      code: 200,
      message: 'success',
      data: newUser
    });
  },
  
  // 更新用户
  'PUT /api/users/:id': (req: any, res: any) => {
    const { id } = req.params;
    const updateData = req.body;
    const userIndex = userList.list.findIndex((item: any) => item.id === parseInt(id));
    
    if (userIndex !== -1) {
      userList.list[userIndex] = { ...userList.list[userIndex], ...updateData };
      res.json({
        code: 200,
        message: 'success',
        data: userList.list[userIndex]
      });
    } else {
      res.json({
        code: 404,
        message: '用户不存在'
      });
    }
  },
  
  // 删除用户
  'DELETE /api/users/:id': (req: any, res: any) => {
    const { id } = req.params;
    const userIndex = userList.list.findIndex((item: any) => item.id === parseInt(id));
    
    if (userIndex !== -1) {
      userList.list.splice(userIndex, 1);
      res.json({
        code: 200,
        message: 'success',
        data: null
      });
    } else {
      res.json({
        code: 404,
        message: '用户不存在'
      });
    }
  }
};

export default userMock;